
import api from "./../../../common/api";
import locationBehavior from "./../../../behaviors/location";
import utils from "./../../../utils/util";
import constant from '../../../common/constant';
import {
  getActiveStr
} from "./../../../utils/utilsNew";
import * as transferData from "./../../../models/transferData";
const cityMap = require("./../../../utils/city");

Page({
  behaviors: [locationBehavior],

  /**
   * 页面的初始数据
   */
  data: {
    soldOutVisble: false,
    houseItem: {},
    cooperationId: "", //当前电话中的合作id
    isVmShow: false, //虚拟电话弹层
    userInfo: {},
    currentCity: "",
    cityCode: "",
    areaCode:'',
    pageIndex: 0,
    pageSize: 10,
    houseList: [],
    hasMoreList: true,
    search: {},
    filterDistrict: "",
    publishTotal: 0, //上架中
    consultTotal: 0, //谁咨询过我
    downPublishTotal: 0, //已下架
    publishTab: [{
        id: "publishUp",
        label: "上架中"
      },
      {
        id: "publishDown",
        label: "已下架"
      },
    ],
    selectPublishTab: 'publishUp',
    tabSelect: "publish",
    tagList: [],
    tagSelect: [],
    status: [0], //已下架筛选
    isShowHouseList: false,
    filterDistrictOption: {
      label: "区域",
      id: "district",
      range: [
        [{
          label: "区域",
          value: "district",
        }, ],
      ],
    },
    comUnconfirmedRoom: false, //是否存在未确认的房态任务
    isShowPublishTitle: false, //顶部的房态确认入口
    isPublishTitleNum: '', //未确认的房态数量
    myHouseIsNot: false,
    selectedIdList: [], //从新上架

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    getApp().globalData.loginPromise.then(() => {
      let t = this
      if (options.tabSelect) {
        this.setData({
          tabSelect: options.tabSelect
        })
      }
      t.queryMyCooperationCount() //判断有没有发布过房源
      t.cooperationConfirmCount('falst')
      t.initData()
      t.onTabSelectChange(options)
      t.loadUserInfo()
      t.checkCurrentCity()
        .then(() => {
          t.getMyCooperationHouseNum()
            .then(() => {
              t.setData({
                isShowHouseList: true,
              })
              // 当我的房源全部都是已下架   默认选中已下架tab
              // 短信的长链强行跳转到已下架   isSms只有短新链接里面有
              if ((t.data.tabSelect == 'publish' && t.data.publishTotal == 0 && t.data.downPublishTotal !== 0)||(options&&options.isSms)) {
                wx.showLoading({
                  title: "加载中...",
                });
                t.setData({
                  selectPublishTab: 'publishDown'
                })
                t.resetHouseData()
                t.loadHouse()
              }
              if ((t.data.publishTotal && t.data.tabSelect == 'publish') || (t.data.consultTotal && t.data.tabSelect == 'consult')) {
                t.loadHouse()
              }
            })
        })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let t = this
    getApp().globalData.loginPromise.then(() => {
      t.cooperationConfirmCount('falst') //解决全部确认后  入口不消失的问题
      t.myData.pageEnterCount += 1
      if (t.myData.pageEnterCount > 1) {
        let refresh = transferData.getData('isRefreshCooperation')
        transferData.resetData('isRefreshCooperation')
        if (refresh) {
          t.resetHouseData()
          t.loadHouse()
          t.getMyCooperationHouseNum()
          let homePage = getCurrentPages()[0]
          let com = homePage.selectComponent('#cooperation')
          if (com) {
            com.resetHouseData()
            com.loadHouse()
          }
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let t = this;
    t.loadHouse();
  },

  /**
   * 页面滚动触发事件的处理函数
   */
  onPageScroll: function (e) {
  },

  initData(options) {
    let t = this;
    t.myData = {
      pageEnterCount: 0,
      publishTagList: [{
          value: "SALES",
          label: "二手",
        },
        {
          value: "RENT",
          label: "出租",
        },
        {
          value: "CONSULT",
          label: "有人咨询",
        },
        {
          value: "COPY",
          label: "有人复制",
        },
      ],
      consultTagList: [{
          value: "SALES",
          label: "二手",
        },
        {
          value: "RENT",
          label: "出租",
        },
        {
          value: "COPY",
          label: "已复制",
        },
      ],
      pageEnterDown: [{
          value: 1,
          label: "虚假/不可合作",
        },
        {
          value: 2,
          label: "超时未维护房态",
        },
        {
          value: 3,
          label: "自主下架",
        },
      ],
    };
    t.setData({
      tagList: t.myData.publishTagList,
      downTagList: t.myData.pageEnterDown,
    });
  },

  onTabSelectChange(e) {
    let t = this;
    let target = e.type;
    if (target === 'publish') {
      wx.setNavigationBarTitle({
        title: '我的房源'
      })
      wx.gio('track', constant.myCoohousePageView, {
        [constant.PageFrom]: e.name||'首页轮播',
      })
    } else {
      wx.setNavigationBarTitle({
        title: '我咨询过的'
      })
    }
    t.setData({
      tagList: t.myData[`${target}TagList`],
      tagSelect: [],
      tabSelect: target,
      search: {},
      filterDistrict: "",
    });
    t.resetHouseData();
    t.loadHouse();
  },


  // 收索
  onSearchChange(e) {
    let t = this;
    let search = e.detail || {};
    t.resetHouseData();
    t.setData({
      search,
    });
    t.loadHouse();
  },

  // 区域
  onFilterChange(e) {
    let t = this;
    let filter = e.detail;
    if (filter.target === "district") {
      t.setData({
        filterDistrict: filter.result[0].value || "",
        areaCode:filter.result[0].code || "",
      });
    }
    t.resetHouseData();
    t.loadHouse();
  },

  loadHouse() {
    let t = this;
    t[`${t.data.tabSelect}House`]();
  },

  // 我的房源
  publishHouse() {
    let t = this;
    return new Promise((resolve, reject) => {
      let {
        pageIndex,
        pageSize,
        search,
        filterDistrict,
        currentCity,
        hasMoreList,
        tagSelect,
        selectPublishTab,
        status,
        cityCode,
        areaCode
      } = t.data;
      if (!hasMoreList) {
        resolve();
        return;
      }
      wx.showLoading({
        title: "加载中...",
      });
      let currentIndex = pageIndex + 1;
      let isSales = tagSelect.indexOf("SALES") !== -1 ? "SALES" : "";
      let isRent = tagSelect.indexOf("RENT") !== -1 ? "RENT" : "";
      let isTalk = tagSelect.indexOf("CONSULT") !== -1 ? true : false;
      let isCopy = tagSelect.indexOf("COPY") !== -1 ? true : false;
      let delegationType = isSales && isRent ? "" : isSales || isRent;
      api.myCooperationList({
          delegationType,
          talking: isTalk,
          copy: isCopy,
          resblockName: search.type === "name" ? search.value : "",
          keyWords: search.type === "key" ? search.value : "",
          city: filterDistrict==''||filterDistrict==null? '':currentCity,
          area: filterDistrict,
          pageNum: currentIndex,
          pageSize,
          cityCode:filterDistrict==''||filterDistrict==null? '':cityCode,
          areaCode:filterDistrict==''||filterDistrict==null? '':areaCode,
          type: selectPublishTab === "publishDown" ? 1 : '', //type 1 查询已下架房源
          status
        }, (res) => {
          wx.hideLoading();
          if (res && res.data && res.data.isSuccess) {
            let result = res.data.content || {};
            let list = result.list || [];
            let maxIndex = result.lastPage;
            let formatList = list.map((item) => {
              let price = item.totalPrice || 0;
              return {
                sceneType: "publish",
                houseID: item.cooperationId || "",
                houseOldID: item.delId || "",
                houseName: item.resblockName || "",
                houseType: item.delegationType,
                houseImg: item.imgId || "",
                houseArea: item.buildSize ? item.buildSize + "㎡" : "--",
                houseRoom: item.room || 0,
                houseHall: item.hall || 0,
                houseDistrict: item.area || "",
                housePrice: item.delegationType === "SALES" ? price / 10000 : price,
                houseIsVR: item.houSubType === 1 ? true : false,
                houseVRStatus: item.houSubTypeState || 0,
                advisoryNum: item.talking || 0,
                copyNum: item.copy || 0,
                updateTime: item.updateTime ? utils.dateFormat(new Date(item.updateTime), "yyyy.MM.dd") : '',
                type: this.data.selectPublishTab === 'publishDown' ? true : false, //点击已下架的显示操作
                downReason: item.downReason, //下架原因
                cooperationStatus: item.cooperationStatus, //下架类型
                title: item.title, //标题
                consultNum: item.consultNum||0, //访问量
                visitNum: item.visitNum||0, //咨询量
                vistorList: item.vistorList, //访客头像
                downHouseDay:item.downHouseDay||'', //距离后台下架时间
                confirmId:item.confirmId|| '',
                // cooperationStatus: 0  上架  1下架
              };
            });
            if (currentIndex === 1) {
              t.data.houseList = [...formatList];
            } else {
              t.data.houseList.push(...formatList);
            }
            t.setData({
              pageIndex: currentIndex,
              hasMoreList: currentIndex >= maxIndex ? false : true,
              houseList: t.data.houseList,
            });
            resolve();
          } else {
            reject();
          }
        },
        () => {
          reject();
          wx.hideLoading();
        }
      );
    });
  },

  consultHouse() {
    let t = this;
    return new Promise((resolve, reject) => {
      let {
        pageIndex,
        pageSize,
        search,
        filterDistrict,
        currentCity,
        hasMoreList,
        tagSelect,
        cityCode,
        areaCode
      } = t.data;
      if (!hasMoreList) {
        resolve();
        return;
      }
      wx.showLoading({
        title: "加载中...",
      });
      let currentIndex = pageIndex + 1;
      let isSales = tagSelect.indexOf("SALES") !== -1 ? "SALES" : "";
      let isRent = tagSelect.indexOf("RENT") !== -1 ? "RENT" : "";
      let isCopy = tagSelect.indexOf("COPY") !== -1 ? true : false;
      let delegationType = isSales && isRent ? "" : isSales || isRent;
      api.myCooperationTalkingList({
          delegationType,
          copy: isCopy,
          resblockName: search.type === "name" ? search.value : "",
          keyWords: search.type === "key" ? search.value : "",
          city: filterDistrict==''||filterDistrict==null? '':currentCity,
          area: filterDistrict,
          cityCode:filterDistrict==''||filterDistrict==null? '':cityCode,
          areaCode:filterDistrict==''||filterDistrict==null? '':areaCode,
          pageNum: currentIndex,
          pageSize,
        },
        (res) => {
          wx.hideLoading();
          if (res && res.data && res.data.isSuccess) {
            let result = res.data.content || {};
            let list = result.list || [];
            let maxIndex = result.lastPage;
            let formatList = list.map((item) => {
              let price = item.totalPrice || 0;
              return {
                sceneType: "advisory",
                houseID: item.cooperationId || "",
                houseOldID: item.delId || "",
                houseCopyID: item.copyDelId || "",
                houseName: item.resblockName || "",
                houseType: item.delegationType,
                houseImg: item.imgId || "",
                houseArea: item.buildSize ? item.buildSize + "㎡" : "--",
                houseRoom: item.room || 0,
                houseHall: item.hall || 0,
                houseDistrict: item.area || "",
                houseIsCopy: item.copyHouseStatus || false,
                housePrice: item.delegationType === "SALES" ? price / 10000 : price,
                houseIsVR: item.houSubType === 1 ? true : false,
                houseVRStatus: item.houSubTypeState || 0,
                houseStatus: item.cooperationStatus,
                brokerName: getActiveStr(item.realName || "", 6),
                brokerStore: getActiveStr(item.storeAllName || "", 12),
                brokerUnionid: item.houseOwnerUnionId || "",
                userCopyTime: item.copyTime ? utils.dateFormat(new Date(item.copyTime), "yyyy-MM-dd") : "",
                wxMobile: item.wxMobile,
                isPhoneAdvisory: item.haveCommunicateType == 'PHONE' || item.haveCommunicateType == 'BOTH',
                isImAdvisory: item.haveCommunicateType == 'IM' || item.haveCommunicateType == 'BOTH',
                userId:item.houseOwnerId
              };
            });
            if (currentIndex === 1) {
              t.data.houseList = [...formatList];
            } else {
              t.data.houseList.push(...formatList);
            }
            t.setData({
              pageIndex: currentIndex,
              hasMoreList: currentIndex >= maxIndex ? false : true,
              houseList: t.data.houseList,
            });
            resolve();
          } else {
            reject();
          }
        },
        () => {
          reject();
          wx.hideLoading();
        }
      );
    });
  },
  checkCurrentCity() {
    let t = this;
    return new Promise((resolve, reject) => {
      t.getCityBe(true)
        .then((city) => {
          let cityCode = "";
          cityMap.cityObjs.forEach((item) => {
            if (item.city === city) {
              cityCode = item.code || "";
            }
          });
          if (cityCode) {
            t.setData({
              currentCity: city,
              cityCode: cityCode,
            });
          } else {
            t.setData({
              currentCity: "上海市",
              cityCode: "310000",
            });
          }
          resolve();
        })
        .catch(() => {
          t.setData({
            currentCity: "上海市",
            cityCode: "310000",
          });
          resolve();
        });
    });
  },

  resetHouseData() {
    let t = this;
    t.setData({
      houseList: [],
      pageIndex: 0,
      hasMoreList: true,
    });
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 0,
    });
  },

  // 发布合作房源
  onJumpPublish() {
    this.verifyPublish()
      .then(() => {
        this.cooperationConfirmCount()
          .then(() => {
            wx.gio('track', constant.RELEASE_FROM, {
              [constant.RELEASE_HOUSE_INFO]: this.data.tabSelect=='publish'? '我的房源':'我咨询过谁',
            })
            wx.navigateTo({
              url: "/pages/cooperation/publishIndex/publishIndex",
            });
          })

      });
  },

  onJumpConsult() {
    wx.navigateBack({
      delta: 11,
    });
  },


  //上架中标签的点击事件
  onTagChange(e) {
    let t = this;
    let filter = e.detail;
    t.resetHouseData();
    t.setData({
      tagSelect: filter,
    });
    t.loadHouse();
  },

  // 下架中标签的点击事件
  downTagChange(e) {
    let t = this;
    let filter = e.detail;
    t.resetHouseData();
    if(filter&&filter.length===0){
      t.setData({
        status: [0],
      });
    } else {
      t.setData({
        status: filter,
      });
    }
    t.loadHouse();
  },
  loadUserInfo() {
    let t = this;
    return new Promise((resolve, reject) => {
      let sessionUser = getApp().globalData.loginUserInfo.data.content.sessionUser;
      api.queryUserAuthInfo({userId: sessionUser.id,},
        (res) => {
          if (res && res.data && res.data.content) {
            let userInfo = res.data.content;
            t.setData({
              userInfo: {
                avatar: userInfo.avatar || userInfo.wxHeadImg || "/images/default_head.png",
                name: userInfo.realname || "",
                nickname: userInfo.nickname || "",
                auth: userInfo.verified || false,
                phone: userInfo.mobile || "",
              },
            });
            resolve();
          } else {
            reject();
          }
        },
        () => {
          reject();
        }
      );
    });
  },

  // 判断有没有权限
  verifyPublish() {
    let t = this;
    return new Promise((resolve, reject) => {
      let sessionUser = getApp().globalData.loginUserInfo.data.content.sessionUser;
      api.queryUserAuthInfo({
          userId: sessionUser.id,
        }, (res) => {
          if (res && res.data && res.data.content) {
            let userInfo = res.data.content;
            if (userInfo.verified) {
              resolve();
            } else {
              wx.navigateTo({
                url: '/pages/cooperation/editCertification/editCertification',
              })
              reject();
            }
          } else {
            reject();
          }
        },
        () => {
          wx.showToast({
            icon: "none",
            title: "网络错误，请稍后再试~",
          });
        }
      );
    });
  },
  // 0519合作房源优化  是否存在未确认的房态任务
  cooperationConfirmCount(tmp) {
    return new Promise((resolve, reject) => {
      api.cooperationConfirmCount({}, (res) => {
        if (res && res.data && res.data.isSuccess) {
          if (tmp === 'falst') {
            if (res.data.content !== 0) {
              this.setData({
                isShowPublishTitle: true,
                isPublishTitleNum: res.data.content
              })
              resolve();
            } else {
              this.setData({
                isShowPublishTitle: false
              })
              resolve();
            }
          } else {
            if (res.data.content !== 0) {
              this.setData({
                comUnconfirmedRoom: true
              })
              reject();
            } else {
              resolve();
            }
          }

        } else {
          reject();
        }
      }, () => {
        wx.showToast({
          icon: "none",
          title: "网络错误，请稍后再试~",
        });
      });
    });
  },
  // 点击前往确认
  _confirmEvent(e) {
    this.setData({
      comUnconfirmedRoom: false
    })
    wx.navigateTo({
      url: "/pages/cooperation/houseStatusUpdate/houseStatusUpdate",
    });
  },
  // 暂不确认
  _cancelEvent(e) {
    this.setData({
      comUnconfirmedRoom: false
    })
  },

  getMyCooperationHouseNum() {
    let t = this;
    return new Promise((resolve, reject) => {
      api.getMyCooperationHouseNum({}, (res) => {
          if (res && res.data && res.data.content) {
            let result = res.data.content;
            t.setData({
              publishTotal: result.myPushCooperationNum, //上架中
              consultTotal: result.myTalkingCooperationNum, //谁咨询过我
              downPublishTotal: result.myDownCooperationNum //已下架
            });
            resolve();
          } else {
            resolve();
          }
        },
        () => {
          resolve();
        }
      );
    });
  },

  // 选择下架原因
  onSoldHide(e) {
    let t = this;
    const {
      label,
      isConfirm
    } = e.detail;
    this.setData({
      soldOutVisble: false
    });

    if (isConfirm) {
      const cooperationId = this.data.houseItem.cooperationId;
      api.downMyCooperation({
          cooperationId,
          downReason: label
        },
        (res) => {
          if (res && res.data && res.data.isSuccess) {
            transferData.setData("isRefreshCooperation", true);
            t.resetHouseData();
            t.loadHouse();
            t.getMyCooperationHouseNum();
            t.cooperationConfirmCount('falst')
          } else {
            wx.showToast({
              icon: "none",
              title: "下架失败，请稍后再试~",
            });
          }
        },
        () => {
          wx.showToast({
            icon: "none",
            title: "下架失败，请稍后再试~",
          });
        }
      );
    }
  },

  // 下架合作
  onUnShelve(e) {
    this.verifyPublish()
      .then(() => {
        let id = e.detail;
        let value = this.data.houseList.find((v) => v.houseID == id)
        this.setData({
          soldOutVisble: true,
          houseItem: {
            cooperationId: value.houseID,
            resblockName: value.houseName,
            delegationType: value.houseType,
            totalPrices: value.houseType == 'SALES' ? value.housePrice * 10000 : value.housePrice,
            buildSize: value.houseArea.replace('㎡', ''),
            room: value.houseRoom,
            hall: value.houseHall,
          }
        })
      });
  },

  //点击到房态确认页面
  roomConfirm() {
    wx.navigateTo({
      url: "/pages/cooperation/houseStatusUpdate/houseStatusUpdate",
    });
  },



  // =====================0601合作房源优化==============================
  selectPublishTabcLICK(e) { //点击上架和下架
    let t = this;
    let target = e.detail.id;
    if (t.data.selectPublishTab === target) return;
    t.setData({
      tagList: t.myData[`${target}TagList`],
      tagSelect: [],
      status:[0],
      selectPublishTab: e.detail.id,
      search: {},
      filterDistrict: "",
      areaCode:""
    });
    t.getMyCooperationHouseNum()
    t.resetHouseData()
    t.loadHouse();
  },

  queryMyCooperationCount() { //判断有没有发布过房源
    let t = this;
    return new Promise((resolve, reject) => {
      api.queryMyCooperationCount({}, (res) => {
        if (res && res.data !== 0) {
          t.setData({
            myHouseIsNot: true
          })
          resolve();
        } else {
          resolve();
        }
      }, () => {
        resolve();
      });
    });
  },
  handleOnBack(e) { // 重新上架
    let t = this;
    this.verifyPublish()
      .then(() => {
        wx.showModal({
          title: '提示',
          content: '是否重新上架此房源？',
          confirmColor: '#E45F58',
          success(res) {
            if (res.confirm) {
              t.setData({
                selectedIdList: [e.detail],
              })
              return new Promise((resolve, reject) => {
                api.publishCooperationHouse(t.data.selectedIdList, ({
                    data
                  }) => {
                    if (data.isSuccess) {
                      t.resetHouseData();
                      t.loadHouse();
                      t.getMyCooperationHouseNum();
                      resolve();
                    } else {
                      wx.showToast({
                        icon: "none",
                        title: "上架失败，请稍后再试~",
                      });
                      reject();
                    }
                  },
                  () => {
                    wx.showToast({
                      icon: "none",
                      title: "上架失败，请稍后再试~",
                    });
                    reject();
                  }
                );
              });
            } else if (res.cancel) {}
          }
        })
      })
  }
});